package scala.for_the.impatient

import scala.math.Pi

/**
  * Created by shichen on 2017/5/24.
  */

class PatternMatch {
  def switch(): Unit = {
    var sign = 0
    var ch:Char = '+'
    ch match {
      case '+' => sign = 1
      case '-' => sign = -1
      case _ => sign = 0
    }
    println(sign)

    ch = '-'
    sign = ch match {
      case '+' => 1
      case '-' => -1
      case _ => 0
    }
    println(sign)

    //guard
    var digit = 0
    ch = '9'
    ch match {
      case '+' => sign = 1
      case '-' => sign = -1
      case _ if Character.isDigit(ch) => digit = Character.digit(ch,10)
      case _ => sign = 0
    }
    println(digit)

    var x = 3.14
    x match {
      case Pi => println("x is Pi") //scala知道Pi是常量，不是变量，变量要以小写开头
      case _ => println("not Pi")
    }

    /*
    var obj = 1
    obj match {
      case x:Int => x
      case s:String => Integer.parseInt(s)
      case _:BigInt => Int.MaxValue
    }
    */

    //////////////////////// 匹配数组
    var arr = Array(0,1,2)
    var s = arr match {
      case Array(0) => "0" //匹配包含0的数组
      case Array(x,y) => x + " " + y //匹配任何带有2个元素的数组
      case Array(0,_*) => "0 ..." //匹配任何以0开始的数组
    }
    println(s)

    ////////////////////for中的模式
    import scala.collection.JavaConversions.propertiesAsScalaMap
    for ((k,v) <- System.getProperties) {
      println(k + " -> " + v)
    }

    //for ((k,v) <- System.getProperties if v == "") println(k)
  }


}

object ch14_pattern_match {

  def t_pattern_match(): Unit = {
    val p = new PatternMatch
    p.switch()
  }
}
